import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:luckdragon/control/serverControl.dart';
import 'package:luckdragon/db.dart';

import 'dart:convert';

void main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'luck dragon',
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: HomePage(title: 'Luck Dragon'),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Widget> serverControls = [];

  _load() async {
    try {
      serverControls.clear();
      var servers = await queryStrs("servers");
      var widgets = servers!.map((e) async {
        var server = await queryStr(e);
        var jsonServer = jsonDecode(server!);
        return serverControl(
          ip: jsonServer["ip"],
          port: jsonServer["port"],
          remarks: jsonServer["remarks"],
        );
      });
      for (var i = 0; i < widgets.toList().length; i++) {
        serverControls.add(await widgets.toList().elementAt(i));
      }
    } catch (e) {}
  }

  @override
  initState() {
    super.initState();
    setState(() {
      _load();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: TextStyle(fontWeight: FontWeight.w300),
          textAlign: TextAlign.center,
        ),
        actions: <Widget>[
          IconButton(
              onPressed: () async {
                final texts = await showTextInputDialog(
                  context: context,
                  textFields: [
                    DialogTextField(
                      hintText: 'ip',
                      validator: (value) =>
                          value!.isEmpty ? 'Input Error' : null,
                    ),
                    DialogTextField(
                      hintText: 'prot',
                      validator: (value) =>
                          value!.isEmpty ? 'Input Error' : null,
                    ),
                    DialogTextField(
                      hintText: 'Remarks',
                      validator: (value) =>
                          value!.isEmpty ? 'Input Error' : null,
                    ),
                  ],
                  title: 'Add Server',
                  message: 'example 192.168.0.1:9013',
                  autoSubmit: true,
                );
                String ip = "";
                String port = "";
                String remarks = "";
                try {
                  ip = texts!.elementAt(0);
                  port = texts.elementAt(1);
                  remarks = texts.elementAt(2);

                  var serverInfo = {"ip": ip, "port": port, "remarks": remarks};
                  var jsonStr = json.encode(serverInfo);

                  List<String> servers = [];

                  bool _Success0 = true;
                  bool _Success1 = true;
                  try {
                    servers = (await queryStrs("servers"))!;
                    if (servers.length > 0) {
                      servers.add(ip);
                      _Success0 = (await addStrs("servers", servers))!;
                      _Success1 = (await addStr(ip, jsonStr))!;
                    } else {
                      servers.add(ip);
                      _Success0 = (await addStrs("servers", servers))!;
                      _Success1 = (await addStr(ip, jsonStr))!;
                    }
                  } catch (e) {
                    servers.add(ip);
                    _Success0 = (await addStrs("servers", servers))!;
                    _Success1 = (await addStr(ip, jsonStr))!;
                  }

                  if (_Success0 && _Success1) {
                    setState(() {
                      _load();
                    });
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text("$ip add Server Success"),
                      ),
                    );
                  }
                } catch (e) {}
              },
              icon: Icon(
                FontAwesomeIcons.plus,
                color: Colors.white,
              ))
        ],
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: ListView(
            children: serverControls,
          ),
        ),
      ),
    );
  }
}
